package com.voxel.sense.infomsg.module.firm.details.chars;


import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.example.com.common.utils.ScreenUtils;
import com.example.com.common.utils.SizeUtils;
import com.example.com.common.utils.TimeUtils;
import com.example.com.common.utils.constants.TimeConstants;
import com.example.com.common.view.recycler.RecyclerAdapter;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.MultiItemBean;
import com.voxel.sense.infomsg.data.bean.RealCharBean;
import com.voxel.sense.infomsg.data.bean.RealDataBean;
import com.voxel.sense.infomsg.data.bean.RealDataHeadBean;
import com.voxel.sense.infomsg.utils.manager.BarCharManager;
import com.voxel.sense.infomsg.utils.manager.LineChartManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import cc.sayaki.widget.PlumbTextView;
import cyy.example.com.facotry.constants.Constants;

/**
 * 企业采集元素表格的适配器
 * Created by chenyiyao on 2017/11/9.
 */

public class ResourceChartAdapter extends RecyclerAdapter<MultiItemBean> {
    //企业采集到的元素个数，用来将图和表分开 超标数据

    public ResourceChartAdapter(AdapterListener<MultiItemBean> listener) {
        super(listener);
    }


    @Override
    protected int getItemViewType(int position, MultiItemBean realTimeDataBean) {
        //小于mElementCount个数的，则是表格数据，否则为图标
        int type = realTimeDataBean.getType();
        int layout;
        switch (type) {
            case Constants.HEAD_TYPE:
            case Constants.NORMAL_TYPE:
                layout = R.layout.item_recycler_source_form;
                break;
            case Constants.REAL_TABLE_CHAR_TYPE:
                layout = R.layout.item_recycler_real_data_char;
                break;
            default:
                layout = R.layout.item_recycler_source_form;
                break;
        }
        return layout;
    }

    @Override
    protected RecyclerAdapter.ViewHolder onCreateViewHolder(View root, int viewType) {
        RecyclerAdapter.ViewHolder holder;
        if (viewType == R.layout.item_recycler_source_form) {
            holder = new NorLineViewHolder(root);
        } else if (viewType == R.layout.item_recycler_real_data_char) {
            holder = new BarCharViewHolder(root);
        } else {
            holder = new ViewHolder(root);
        }
        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
        super.onBindViewHolder(holder, position);
    }


    //折线
    static class ViewHolder extends RecyclerAdapter.ViewHolder<MultiItemBean<RealCharBean>> {
        View root;
        @BindView(R.id.line_chart)
        LineChart line_chart;

        public ViewHolder(View itemView) {
            super(itemView);
            root = itemView;
        }

        @Override
        protected void onBind(MultiItemBean<RealCharBean> realTimeDataBean) {
            RealCharBean data = realTimeDataBean.getData();

            List<RealCharBean.ValueBean> paramValue = data.getParamValue();
            String paramUnit = data.getParamUnit();//单位
            //初始化图标的坐标点
            ArrayList<Entry> yValue = new ArrayList<>();
            for (RealCharBean.ValueBean bean : paramValue) {
                try {
                    Date date = TimeUtils.getDate(bean.getTime(), 0, TimeConstants.SEC);
                    int x = date.getHours();
                    float y = Float.parseFloat(bean.getValue());
                    String value = bean.getValue();
                    Entry entry = new Entry(x, y);
                    //添加坐标点的额外数据
                    String markerText = value + paramUnit + "(" + TimeUtils.date2String(date,
                            new SimpleDateFormat("yyyy-MM-dd")) + ")";
                    String[] strings = {bean.getValue(), markerText};
                    entry.setData(strings);
                    yValue.add(entry);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //表格右下角描述信息--显示单位
            Description description = new Description();
            description.setText(paramUnit);
            int screenWidth = ScreenUtils.getScreenWidth();
            int widthDp = SizeUtils.px2dp(screenWidth);
            //一定单位文本的位置及大小，该传入单位的是dp值，右下角0，0
            description.setTextSize(12);
            description.setYOffset(245);
            description.setXOffset(widthDp - 80);
            line_chart.setDescription(description);

            //设置底部描述信息--折线的名称
            LineChartManager.setLineName(data.getParamName());
            //创建一条折线的图表
            LineChartManager.initSingleLineChart(root.getContext(), line_chart, yValue);
        }
    }

    static class NorLineViewHolder extends RecyclerAdapter.ViewHolder<MultiItemBean> {
        @BindView(R.id.tv_element)
        TextView tv_element;//元素
        @BindView(R.id.tv_numb)
        TextView tv_numb; //数值

        private NorLineViewHolder(View itemView) {
            super(itemView);
        }

        @Override
        protected void onBind(MultiItemBean tableDataBean) {
            if (tableDataBean.getType() == Constants.HEAD_TYPE) {
                RealDataHeadBean data = (RealDataHeadBean) tableDataBean.getData();
                tv_element.setText(data.getOneColumn());
                tv_numb.setText(data.getTwoColumn());
            } else {
                RealDataBean data = (RealDataBean) tableDataBean.getData();
                tv_element.setText(data.getParamName());
                if (!TextUtils.isEmpty(data.getParamUnit())) {
                    tv_numb.setText(data.getValue() + "(" + data.getParamUnit() + ")");
                } else {
                    tv_numb.setText(data.getValue());
                }
            }
        }
    }

    //柱形
    static class BarCharViewHolder extends RecyclerAdapter.ViewHolder<MultiItemBean<List<RealDataBean>>> {
        @BindView(R.id.ptv_left)
        PlumbTextView ptv_left;
        @BindView(R.id.ptv_right)
        PlumbTextView ptv_right;
        @BindView(R.id.bar_chart)
        BarChart bar_chart;

        private BarCharViewHolder(View itemView) {
            super(itemView);
        }

        @Override
        protected void onBind(MultiItemBean<List<RealDataBean>> bean) {
            List<RealDataBean> data = bean.getData();
            Description description = new Description();
            description.setText("");
            bar_chart.setDescription(description);

            float rightAxisMax = 0;

            if (data != null && data.size() > 0) {
                //图的数据集
                List<IBarDataSet> barDataSets = new ArrayList<>();

                StringBuffer bufferLeft = new StringBuffer();
                StringBuffer bufferRight = new StringBuffer();
                int i = 0;
                //重新进行排序
                Collections.sort(data, new Comparator<RealDataBean>() {
                    @Override
                    public int compare(RealDataBean o1, RealDataBean o2) {
                        String value = o1.getValue();
                        String value1 = o2.getValue();

                        if(TextUtils.isEmpty(value) ||"null".equals(value)){
                            value = "0.0";
                        }
                        if(TextUtils.isEmpty(value1) || "null".equals(value1)){
                            value1 = "0.0";
                        }
                        try {
                            Float v = Float.parseFloat(value);
                            Float v1 = Float.parseFloat(value1);
                            return v1.compareTo(v);
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        return value1.compareTo(value);
                    }
                });
                float partingNumb = 0;
                //组装数据
                for (RealDataBean realData : data) {
                    String value = realData.getValue();
                    if(TextUtils.isEmpty(value)){
                        value = "0";
                    }
                    try {
                        float v = Float.parseFloat(value);
                        String paramName = realData.getParamName();

                        int color;//颜色
                        int style = i / 5;
                        int item = i % 5;
                        color = getBarColor(style, item);//获取每条柱形图的颜色

                        i++;
                        List<BarEntry> entryList = new ArrayList<>();
                        if (v > 5) {
                            //大于5的对应左轴
                            //左右两旁的描述文字
                            bufferLeft.append(paramName + "、");
                            entryList.add(new BarEntry(i, v, realData));
                            //每个BarDataSet 都代表一条柱形
                            BarDataSet leftDataSet = new BarDataSet(entryList, i + "." + paramName);
                            leftDataSet.setColors(color);
                            //依赖左边的y轴
                            leftDataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
                            barDataSets.add(leftDataSet);
                        } else {
                            if (partingNumb == 0) {
                                partingNumb = i;
                            }
                            rightAxisMax = rightAxisMax >= v ? rightAxisMax : v;
                            //小于5的对应右轴线
                            bufferRight.append(paramName + "、");
                            entryList.add(new BarEntry(i+1, v, realData));
                            BarDataSet rightDataSet = new BarDataSet(entryList, (i+1)+ "." + paramName);
                            rightDataSet.setColor(color);
                            //小于5的数值依赖右边的y轴
                            rightDataSet.setAxisDependency(YAxis.AxisDependency.RIGHT);
                            barDataSets.add(rightDataSet);
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
                if (partingNumb != 0) {
                    LimitLine ll = new LimitLine(partingNumb);
                    //分界线
                    ll.setLineColor(ptv_left.getContext().getResources().getColor(R.color.orange_800));
                    ll.setLineWidth(1f);
                    bar_chart.getXAxis().addLimitLine(ll);
                }

                YAxis axisRight = bar_chart.getAxisRight();
                //右边轴最大值
                axisRight.setAxisMaximum((rightAxisMax != 0) ? rightAxisMax : 5);

                //设置文本，且去除文本末尾的、符号
                if (bufferLeft.length() > 0) {
                    ptv_left.setText(bufferLeft.deleteCharAt(bufferLeft.length() - 1).toString());
                }
                if (bufferRight.length() > 0) {
                    ptv_right.setText(bufferRight.deleteCharAt(bufferRight.length() - 1).toString());
                }

                //设置数据
                BarCharManager.initBarChart(bar_chart, barDataSets);

            }
        }

        /**
         * 获取柱形图的颜色
         */
        private int getBarColor(int style, int item) {
            int color;
            if (style == 0) {
                color = ColorTemplate.LIBERTY_COLORS[item];
            } else if (style == 1) {
                color = ColorTemplate.JOYFUL_COLORS[item];
            } else {
                color = ColorTemplate.PASTEL_COLORS[item];
            }
            return color;
        }
    }
}
